package org.dsun.mvc.config;

import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dsun.json.bean.JsonValue;
import org.dsun.json.read.ReadJson;
import org.dsun.mvc.entity.Action;

public class ActionConfig {
	
	private static ActionConfig instance=null;
	
	private Map<String, String> resultTypes=new HashMap<String, String>();
	private Map<String, Action> actions=new HashMap<String, Action>();

	static{
//		long now= new Date().getTime();
		instance=new ActionConfig();
		try {
			JsonValue jv=new ReadJson(ActionConfig.class.getResourceAsStream("/dsun.json")).read();
			List<String> includeFiles=new ArrayList<String>();
			includeFiles=ConfigUtil.fetchIncludeFiles(jv);
			instance.resultTypes.putAll(ConfigUtil.fetchResultTypes(jv));
			try {
				instance.actions.putAll(ConfigUtil.fetchActions(jv, instance.resultTypes));
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
			for(String file:includeFiles){
				JsonValue jf=new ReadJson(ActionConfig.class.getResourceAsStream(file)).read();
				instance.resultTypes.putAll(ConfigUtil.fetchResultTypes(jf));
				try {
					instance.actions.putAll(ConfigUtil.fetchActions(jf, instance.resultTypes));
				} catch (InstantiationException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				}
			}
//			System.out.println(new Date().getTime()-now);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
	
	protected ActionConfig() {
		
	}
	
	public static ActionConfig getInstance(){
		return instance;
	}
	
	public void installResultType(String type,String classname){
		resultTypes.put(type, classname);
	}
	
	public String fetchResultType(String type){
		return resultTypes.get(type);
	}

	public void installAction(String actionPath,Action action){
		actions.put(actionPath, action);
	}
	
	public Action fetchAction(String actionPath){
		return actions.get(actionPath);
	}

	public Map<String, String> getResultTypes() {
		return resultTypes;
	}

	public Map<String, Action> getActions() {
		return actions;
	}
	
	public static void main(String[] args) {
		System.out.println("good");
	}
	
}
